import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Button,
  Modal,
  message,
  Badge,
  Divider,
  Table,
  Popconfirm,
  Radio,
  TreeSelect,
  Icon,
  Menu,
  Dropdown,
} from 'antd';
import TableList from '@/components/TableList';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import ChoosePerson from '@/components/BindPerson/ChoosePerson';
import UserTable from '@/components/BindPerson/UserTable';
import HasUser from '@/components/BindPerson/HasUser';
import {ruleP, nameMaxLength,remarkMaxLength} from '@/utils/rule'
import styles from '../search.less';
const TreeNode = TreeSelect.TreeNode;
const FormItem = Form.Item;
const { TextArea } = Input;
const { Option } = Select;
const RadioGroup = Radio.Group;
const statusMap = ['success', 'error'];
const status = ['启用', '禁用'];
const formLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 17 },
};

const viewLayout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};

const CreateForm = Form.create()(props => {

   const {
    modalVisible,
    form,
    addDataFn,
    updateFn,
    handleModalVisible,
    text,
    isDetail,
    userCode,
    detailsData,
    adminData,
    handleBindUserVisible,
    groupMember,
    deleteGMember,
    handleMemberVisible,
    handleHasUserVisible,
    } = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      if(!text && !(groupMember.length&&groupMember[0].userCode)){
        message.warning('请选择人员')
        return;
      }
      const obj = {}
      if(text) {
        updateFn(Object.assign(obj,fieldsValue),text)
      }else{
        addDataFn(Object.assign(obj,fieldsValue));
      }
    });
  };
  const onChange = (v) =>{}

  if(isDetail){
  return (
   <Modal
      destroyOnClose
      width={800}
      title="查看详情"
      visible={modalVisible}
      onCancel={() => handleModalVisible()}
      footer={[
        <Button key="back" type="primary" onClick={() => handleModalVisible()}>返回</Button>
      ]}
      className={styles.viewMore}
      >

     <Row>
       <Col md={12}>
         <FormItem {...viewLayout} label="自定义组名">
           {text.groupName}
         </FormItem>
       </Col>

       <Col md={12}>
         <FormItem {...viewLayout} label="自定义组管理员">
           {text.adminUserName}
         </FormItem>
       </Col>
       <Col md={24}>
         <FormItem labelCol={{span:4}} wrapperCol={{span:20}} label="自定义组内成员">
            <span>{text.userCodes}</span>&nbsp;&nbsp;
            {text.userCodes?<a onClick={() => handleMemberVisible(true)} >查看详细</a>:null}
         </FormItem>
       </Col>

       <Col md={24}>
         <FormItem labelCol={{span:4}} wrapperCol={{span:20}} label="自定义组描述">
           {text.remark}
         </FormItem>
       </Col>

     </Row>

    </Modal>
        )
  }else{
    return (
      <Modal
        destroyOnClose
        width={640}
        title={text?'编辑自定义组':'新增自定义组'}
        visible={modalVisible}
        onOk={okHandle}
        onCancel={() => handleModalVisible()}
        maskClosable={false}
      >
        <FormItem {...formLayout} label="自定义组名">
          {form.getFieldDecorator('groupName', {
            rules: [{required: true,message:'自定义组名不能为空'},{max:nameMaxLength()[0],message:nameMaxLength()[1]}],initialValue: text&&text.groupName||''
          })(<Input placeholder="请输入"/>)}
        </FormItem>

        <FormItem {...formLayout} label="自定义组管理员">
        {form.getFieldDecorator('adminUserCode', {
          initialValue: text&&text.adminUserCode?text.adminUserCode.split(','):[]
        })(<Select mode="multiple" placeholder="请选择" style={{ width: '100%' }}>
        {
          adminData&&adminData.length&&adminData.map((v) => {
              return (<Option key={v.userId} value={v.userCode}>{v.userName}</Option>)
            })
          }
        </Select>)}
      </FormItem>

        <FormItem {...formLayout} label="自定义组内成员">
          {form.getFieldDecorator('userCodeList',{initialValue: text&&text.userCodeList||[]})(
            <Fragment>
            <Button type="primary" onClick={() => handleBindUserVisible(true)} >请选择</Button>
            <div>{groupMember&&groupMember.length?groupMember.slice(0,3).map((v,i) => {
              return <span key={i} style={{marginRight:'20px',}}>{v.userName} {/*<Icon type="close-circle" onClick={() => deleteGMember(i)} />*/}</span>
            }):null}{groupMember&&groupMember.length&&groupMember.length>3?'...':''}
              {groupMember&&groupMember.length&&groupMember.length>0?<a onClick={() => handleHasUserVisible(true)} style={{marginLeft:25}}>查看已选人员</a>:null}
              </div>
            </Fragment>
          )}
        </FormItem>

        <FormItem {...formLayout} label="状态" style={{display: text == null ? 'none' : 'block',}}>
            {form.getFieldDecorator('status',{initialValue: text&&text.status
            })(
              <Radio.Group>
                <Radio value={0}>
                  启用
                </Radio>
                <Radio value={1}>
                  禁用
                </Radio>
              </Radio.Group>
            )}
          </FormItem>

        <FormItem {...formLayout} label="自定义组描述">
          {form.getFieldDecorator('remark',{rules: [{max:remarkMaxLength()[0],message:remarkMaxLength()[1]}],initialValue: text&&text.remark||''})(<TextArea
            style={{minHeight: 32}}
            rows={2}
          />)}
        </FormItem>
      </Modal>

  ) ; }
});

@Form.create()

/* eslint react/no-multi-comp:0 */
@connect(({ defineGroup, loading }) => ({
  defineGroup,
  loading: loading.models.defineGroup,
}))
@Form.create()
class defineGroup extends PureComponent {
  state = {
    modalVisible: false,
    updateModalVisible: false,
    expandForm: false,
    selectedRows: [],
    formValues: {},
    isDetail: false,
    detailsData: {},
    text: {},
    adminData: [],
    bindUserVisible: false, //绑定用户
    personData: {}, //人员数据
    groupMember: [],
    memberVisible: false, // 组内成员
    memberId: '', // 请求人员接口需要
    hasUserVisible: false,
  };


  columns = [
    {
      title: '自定义组名',
      dataIndex: 'groupName',
    },
    {
      title: '自定义组管理员',
      dataIndex: 'adminUserName',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render(val) {
        return <Badge status={statusMap[val]} text={status[val]} />;
      },
    },
    {
      title: '操作',
      render: (text, record) => (
        <Fragment>
          <a onClick={() => this.openDetailsPage(true,text)}>详情</a>
          <Divider type="vertical" />
          <Dropdown
            overlay={
              <Menu>
                <Menu.Item onClick={() => this.handleModalVisible(true, record)}>编辑</Menu.Item>
                <Menu.Item onClick={() => this.deleteData(text.id)}>删除</Menu.Item>
              </Menu>
            }
          >
            <a>更多 <Icon type="down"/></a>
          </Dropdown>
        </Fragment>
      ),
    },
  ];

  openDetailsPage = (flag,text) => {
    this.handleModalVisible(true,text);
    this.setState({
      isDetail: true,
      text: text,
      memberId: text.id,
    },
    ()=>{
    this.idQuery();
    });
  };

  // 详情接口--人员
  idQuery(pageSize=999,pageNum=0) {
    const id = this.state.memberId;
    const { dispatch } = this.props;
    const values = {
      id,
      pageSize: pageSize,
      pageNum: pageNum,
    };
    dispatch({
      type: 'defineGroup/queryId',
      payload: values,
      callback: (res) => {
        if(res.result == "ok") {
          this.setState({
            detailsData: res.data,
            groupMember: res.data.dataList,
          })
        }else {
          Modal.error({
            title: '操作失败',
            content: res.msg,
          });
        }
      }
    });
  }
  // 删除方法
  deleteData = (id) => {
    Modal.confirm({
      title: '删除',
      content: '您确定要删除以下数据吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => this.handleThisRowDelete(id),
    });
  };

  batchDelete = (rows=[]) => {
    const ids = rows.map((item) => {
      return item.id;
    }).join(",");
    this.deleteData(ids); //批量删除
  };

  handleThisRowDelete = (id) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'defineGroup/remove',
      payload: {id},
      callback: (res) => {
        if(res.result == "ok") {
          Modal.success({title: res.msg});
          dispatch({
            type: 'defineGroup/queryList',});
          this.setState({selectedRows: []})
        }else {
          Modal.error({title: '操作失败',content: res.msg});
        }
      },//callback
    });
  }

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  // 分页查询列表
  pageList(data,pageSize=10,pageNum=0) {
    const { dispatch } = this.props;
    const values = {
      groupName: data && data.groupName || '',
      adminUserName: data && data.adminUserName || '',
      pageSize: pageSize,
      pageNum: pageNum,
    };
    dispatch({
      type: 'defineGroup/queryList',
      payload: values,
    });
  }

  // 点击树查询人员接口
  getList(res,pageSize=5,pageNum=0) {
    const { dispatch } = this.props;
    const values = {
      orgId: (res && res.orgId),
      id: (res && res.id) || '',
      userName: (res && res.userName) || '',
      userCode: (res && res.userCode) || '',
      pageSize: pageSize,
      pageNum: pageNum,
    };
    dispatch({
      type: 'defineGroup/queryUserList',
      payload: values,
      callback: (obj) => {
        if(obj.result == "ok") {
          this.setState({
            personData: obj.data,
          })
        }
      },
    });
  }

componentDidMount() {
    this.pageList();
    this.getTree();
    this.adminMothod();
}

// 管理员
adminMothod() {
  const { dispatch } = this.props;
  dispatch({
    type: 'defineGroup/admin',
    callback: (res) => {
      if(res.result == "ok") {
        this.setState({
          adminData: res.data
        })
      }else {
        Modal.error({
          title: '操作失败',
          content: res.msg,
        });
      }
    },
  });
}

// 获取人员组织树
getTree() {
  const { dispatch } = this.props;
  dispatch({
    type: 'defineGroup/getTree',
  });
}

  handleSearch = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      //点击查询
      this.setState({
        formValues: fieldsValue,
      })
      this.pageList(fieldsValue);
    });
  };

// 新增弹框的显示和隐藏
  handleModalVisible = (flag,text) => {
    const newArr = [];
    this.setState({
      modalVisible: !!flag,
      text: text,
      isDetail: false,
      userCode: text&&text.userCode?text.userCode:'',
    });   
    if(text&&flag) {
      newArr.push(text);
      this.setState({
        memberId: text&&text.id,
        groupMember: newArr,
      },
      ()=>{
        // 查询了两次，先把这个注释掉，有问题再放出来
        // this.idQuery();
      });
    }else{
      this.setState({
        groupMember: [],
      })
    }
  };

  // 绑定用户弹框显示和隐藏
  handleBindUserVisible = (flag,selectedRows) => {
    this.setState({
      bindUserVisible: !!flag,
    });
    if(!flag){
      const { groupMember } = this.state;
      const concatArr = selectedRows?groupMember.concat(selectedRows):groupMember;
      // 去重
      const result = [];
      let obj = {};
      for(var i =0; i<concatArr.length; i++){
         if(!obj[concatArr[i].userCode]){
            result.push(concatArr[i]);
            obj[concatArr[i].userCode] = true;
         }
      }
      this.setState({
        personData: {},
        groupMember: result,
      })
    }
  };

  // 组内成员弹框
  handleMemberVisible = (flag) => {
    this.setState({
      memberVisible: !!flag,
    });
  };

   // 已选择成员详情弹框
  handleHasUserVisible = (flag) => {
    this.setState({
      hasUserVisible: !!flag,
    });
  };


  deleteGMember = (userCode) => {
    const { groupMember } = this.state;
    let copyGM = [...groupMember];
    copyGM.map((v,i) => {
      if(v.userCode == userCode) {
        copyGM.splice(i,1);
      }
    })
    this.setState({
        groupMember: copyGM,
      })
  }

  // 更新接口
  updateFn = (fields,text) => {
    const { dispatch } = this.props;
    const { groupMember } = this.state;
    const arrUserCodeList = groupMember&&groupMember.length&&groupMember.map((v)=>{
      return v.userCode
    }).join(",");
    const params = {
      id: text.id,
      groupName: fields.groupName,
      adminUserCode:fields.adminUserCode,
      remark: fields.remark,
      userCodeList:arrUserCodeList,
      status: fields.status
    }
    dispatch({
      type: 'defineGroup/update',
      payload: params,
      callback: (res) => {
        if(res.result == "ok") {
          Modal.success({
            title: res.msg,
          });
          this.pageList();
        }else {
          Modal.error({
            title: '操作失败',
            content: res.msg,
          });
        }
      },
    });
    this.handleModalVisible();
  };

  // 增加接口
  addDataFn = (fields) => {
    const { dispatch } = this.props;
    const { groupMember } = this.state;
    // const arrUserCodeList = groupMember&&groupMember.length?groupMember.map((v)=>{
    //   return v.userCode
    // }).join(","):null
    const arrUserCodeList = groupMember&&groupMember.length&&groupMember.map((v)=>{
      return v.userCode
    }).join(",");

    const params = {
        groupName: fields.groupName,
        adminUserCode:fields.adminUserCode,
        remark: fields.remark,
        userCodeList:arrUserCodeList,
        status: fields.status
    }
    dispatch({
      type: 'defineGroup/add',
      payload: params,
      callback: (res) => {
        if(res.result == "ok") {
          Modal.success({
            title: res.msg,
          });
          this.pageList();
        }else {
          Modal.error({
            title: '操作失败',
            content: res.msg,
          });
        }
      },
    });
    this.handleModalVisible();
  };



  renderSimpleForm() {
    const {
      form: {getFieldDecorator},
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{md: 8, lg: 24, xl: 48}}>
          <Col md={8} sm={24}>
            <FormItem label="自定义组名">
              {getFieldDecorator('groupName')(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <FormItem label="自定义组管理员">
              {getFieldDecorator('adminUserName')(<Input placeholder="请输入"/>)}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

   handleStandardTableChange(pagination, filters, sorter) {
    const {formValues} = this.state;
    // 分页请求
    this.pageList(formValues,pagination.pageSize,pagination.current-1);
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  render() {
    const {
      defineGroup: { data, treeDataList },
      loading,
    } = this.props;
    const {
      selectedRows,
      modalVisible,
      updateModalVisible,
      text,
      isDetail,
      detailsData,
      adminData,
      bindUserVisible,
      personData,
      groupMember,
      memberVisible,
      hasUserVisible,
      } = this.state;
    const parentMethods = {
      handleModalVisible: this.handleModalVisible,
      handleBindUserVisible: this.handleBindUserVisible.bind(this),
      addDataFn: this.addDataFn,
      updateFn: this.updateFn,
      isDetail: isDetail,
      deleteGMember: this.deleteGMember.bind(this),
      handleMemberVisible: this.handleMemberVisible.bind(this),
      handleHasUserVisible: this.handleHasUserVisible.bind(this),
    };
    const BindUserMethods = {
      handleBindUserVisible: this.handleBindUserVisible.bind(this),
      getList: this.getList.bind(this),
    }
    const memberMethods = {
      handleMemberVisible: this.handleMemberVisible.bind(this),
      idQuery: this.idQuery.bind(this),
    }
    const hasUserMethods = {
      handleHasUserVisible: this.handleHasUserVisible.bind(this),
      deleteGMember: this.deleteGMember.bind(this),
    }
    return (
      <PageHeaderWrapper title="自定义组">
        <Card bordered={false}>
          <UserTable
            {...memberMethods}
            memberVisible={memberVisible}
            detailsData={detailsData}
           />
           {hasUserVisible?<HasUser
             {...hasUserMethods}
             hasUserVisible={hasUserVisible}
             groupMember={groupMember}
            />:null}
          <ChoosePerson
            {...BindUserMethods}
            bindUserVisible={bindUserVisible}
            treeDataList={treeDataList}
            personData={personData}
            text={text}
          />
          <CreateForm
            {...parentMethods}
            modalVisible={modalVisible}
            text={text}
            detailsData={detailsData}
            adminData={adminData}
            groupMember={groupMember}
          />
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <div className={styles.tableListOperator}>
              <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
                新增
              </Button>
              {selectedRows.length > 0 && (
                <span>
                  <Button onClick={() => this.batchDelete(selectedRows)}>批量删除</Button>
                </span>
              )}
            </div>
            <TableList
              className={styles.tdPadding}
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              columns={this.columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange.bind(this)}
              rowKey={record => record.id}
            />
          </div>
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default defineGroup;
